﻿
namespace ComTools.Helpers
{
    using Ionic.Zlib;
    using System.IO;

    /// <summary>
    /// 用来实现数据压缩的帮助类
    /// </summary>
    public class CompressionHelper
    {
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="str">要压缩的字节数组</param>
        /// <param name="compLevel">压缩等级</param>
        /// <returns>压缩结果</returns>
        public static byte[] DeflateByte(byte[] str, CompressionLevel compLevel)
        {
            if (str == null)
            {
                return null;
            }

            using (var output = new MemoryStream())
            {
                using (var compressor = new DeflateStream(output, CompressionMode.Compress, compLevel))
                {
                    compressor.Write(str, 0, str.Length);
                }
                return output.ToArray();
            }
        }

        /// <summary>
        /// 使用GZIP压缩字节数组
        /// </summary>
        /// <param name="str">要压缩的字节数组</param>
        /// <param name="compLevel">压缩等级</param>
        /// <returns>压缩结果</returns>
        public static byte[] GZipByte(byte[] str, CompressionLevel compLevel)
        {
            if (str == null)
            {
                return null;
            }

            using (var output = new MemoryStream())
            {
                using (var compressor = new GZipStream(output, CompressionMode.Compress, compLevel))
                {
                    compressor.Write(str, 0, str.Length);
                }
                return output.ToArray();
            }
        }
    }
}
